<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 动态分享接口
 */
class BlogShare extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function addBlogShareById($blogId = NULL)
    {
        if (!$blogId) {
            $this->error(__('Parameter %s can not be empty', 'blogId'));
        }
        $blog = model('\app\admin\model\jy\Blog')->where('id', $blogId)->find();
        if (!$blog) {
            $this->error(__('No Results were found'));
        }
        $userId = $this->auth->id;
        Db::startTrans();
        try {
            $row = model('\app\admin\model\jy\BlogShare')->where(['blog_id' => $blogId, 'user_id' => $userId])->find();
            if (!$row) {
                model('\app\admin\model\jy\BlogShare')->insert(['blog_id' => $blogId, 'user_id' => $userId]);
                $blog->share_user_count++;
            }
            $blog->share_count++;
            $blog->update_time = date("Y-m-d H:i:s", time());
            $blog->isUpdate(true)->save();
            Db::commit();
            $this->success('', ['share_count' => $blog['share_count'], 'share_user_count' => $blog['share_user_count']]);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function addBlogShareCountByShareId($shareId = NULL)
    {
        if (!$shareId) {
            $this->error(__('Parameter %s can not be empty', 'shareId'));
        }
        $share = model('\app\admin\model\jy\BlogShare')->where('id', $shareId)->find();
        if (!$share) {
            $this->error(__('No Results were found'));
        }
        $share['click_count'] = $share['click_count'] + 1;
        $share['update_time'] = date("Y-m-d H:i:s", time());
        $share->isUpdate(true)->save();
        $this->success();
    }
}